from kivy import require
from kivymd.app import MDApp
from kivy.uix.screenmanager import Screen, ScreenManager, FadeTransition
from kivy.core.window import Window
from kivy.properties import NumericProperty, StringProperty
from kivymd.uix.boxlayout import MDBoxLayout
from kivy.animation import Animation
from kivy.core.text import LabelBase
from kivy.core.audio import SoundLoader
import os
from itertools import cycle
from kivy.config import Config

require('2.0.0')
Window.size = (360, 612)
Config.set('kivy', 'window_icon', 'assets/image/favicon.ico')
os.environ['KIVY_AUDIO'] = 'ffpyplayer'
LabelBase.register(name='msyh', fn_regular='assets/font/msyh.ttf')
path_to_songs = 'assets/music/'


class MusicScreen(Screen):
    pass


class SongListScreen(Screen):
    pass


class SongCover(MDBoxLayout):
    pausePlay = StringProperty('play')
    songLength = NumericProperty(0)
    songName = StringProperty('')
    angle = NumericProperty()

    anim = Animation(angle=360, d=5, t='linear')
    anim += Animation(angle=0, d=0, t='linear')
    anim.repeat = True
    progress = Animation(value=100, d=100, t='linear')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.songs = [song for song in os.listdir(path_to_songs)]
        self.song_cycle = cycle(self.songs)
        self.songName = next(self.song_cycle)
        self.load()

    def load(self):
        self.music = SoundLoader.load(path_to_songs + self.songName)
        self.music.volume = 0.3
        self.music.loop = True
        self.songLength = self.music.length

    def reload(self, widget):
        self.music.stop()
        self.music.unload()
        self.anim.stop(self)
        self.progress.stop(widget)

    def play_prev(self, widget):
        self.reload(widget)
        r = self.songs.index(self.songName) - 1
        if r < 0:
            self.songName = self.songs[-1]
        else:
            self.songName = self.songs[r]
        self.load()
        self.play(widget)

    def play_next(self, widget):
        self.reload(widget)
        self.songName = next(self.song_cycle)
        self.load()
        self.play(widget)

    def rotate(self):
        if self.anim.have_properties_to_animate(self):
            self.anim.stop(self)
            self.progress.stop(self.widget)
            self.music.stop()
        else:
            self.anim.start(self)
            self.music.play()

    def play(self, widget):
        self.widget = widget
        self.progress.start(widget)
        self.rotate()
        if self.music.state == 'play':
            self.pausePlay = 'pause'
        elif self.music.state == 'stop':
            self.pausePlay = 'play'

class MainApp(MDApp):
    SongCover()
    def build(self):
        sm = ScreenManager(transition=FadeTransition())
        sm.add_widget(MusicScreen(name='main'))
        sm.add_widget(SongListScreen(name='songList'))
        return sm
        # return MusicScreen()


MainApp().run()
